<template>
  <div class="code-editor-page">
    <div class="code-editor-container">
      <!-- 代码编辑器 -->
      <div ref="editorContainer" class="editor-container"></div>
      <!-- 按钮 -->
      <div class="actions">
        <button @click="runCode">运行</button>
        <button @click="resetCode">重置</button>
      </div>
    </div>
    <!-- 渲染器 -->
    <div class="result-container">
      <iframe ref="resultFrame" class="result-frame"></iframe>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { compile } from 'vue-template-compiler';
import * as monaco from 'monaco-editor';
import codeExample from '@/views/Demo/examples/1-1.vue';

export default {
  name: 'CodeEditorPage',
  setup() {
    const editorContainer = ref(null);
    let editorInstance = null;
    const resultFrame = ref(null);
    const contentText = ref(null)

    onMounted(() => {
      initCodeContainer()
      
    });
    // 初始化代码编辑器
    const initCodeContainer = async () => {
      try {
        const response = await fetch('examples/railView/1-1.html');
        contentText.value = await response.text();
        editorInstance = monaco.editor.create(editorContainer.value, {
          value: contentText.value,
          language: 'html',
          theme: 'vs-dark',
        });
        runCode()
      } catch (error) {
        console.error(error);
      }
    }

    const runCode = () => {
      const code = editorInstance.getValue();
      const iframe = resultFrame.value;

      iframe.contentDocument.open();
      iframe.contentDocument.write(code);
      iframe.contentDocument.close();
    };

    const resetCode = () => {
      editorInstance.setValue(contentText.value);
    };

    return {
      editorContainer,
      resultFrame,
      runCode,
      resetCode,
    };
  },
};
</script>

<style>
.code-editor-page {
  display: flex;
  height: 100vh;
  background-color: pink;
}

.code-editor-container {
  flex: 1;
  height: 100%;
}

.editor-container {
  height: 100%;
}

.result-container {
  flex: 1;
  height: 100%;
}

.result-frame {
  width: 100%;
  height: 100%;
  border: none;
}
.actions {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  height: 100px;
  background-color: pink;
}

button {
  margin: 0 8px;
  padding: 8px 16px;
}
</style>
